<template>
  <h1>详情页</h1>
  <hr>
  <h1>{{weibo.nickname}}说了: {{weibo.content}}</h1>
  <p>发布于: {{weibo.created}}</p>
  <hr>
  <el-input v-model:="comment.content" placeholder="请留下你的评论吧!"></el-input>
  <el-button type="primary" @click="post()" style="margin: 10px;">发布评论</el-button>

  <div v-for="c in arr">
    <h4>{{c.nickname}}评论说:{{c.content}}</h4>
    <span>发布于:{{c.created}}</span>
  </div>

</template>

<script setup>
import {onMounted, ref} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";
import router from "@/router";
import qs from "qs";
const weibo = ref({});
onMounted ( () => {
  let id = new URLSearchParams(location.search).get('id');
  loadComments(id);
  // alert(id)
  axios.get('http://localhost:8080/v1/weibos/' + id + '/detail')
      .then((res) => {
        if (res.data.code == 2002){
          weibo.value = res.data.data;
        }
      })

})

const comment = ref({content:''});
const post = ()=> {
  // 获取user 数据
  let user = getUser();

  if (user == null ){
    ElMessage.error('清先登录');
    router.push('/login');
    return;
  }
  //给评论对象设置评论员与微博id
  comment.value.userId = user.id;
  comment.value.weiboId = weibo.value.id;

  let data = qs.stringify(comment.value)

  axios.post('http://localhost:8080/v1/comments/add-new', data)
      .then((res) => {
        if (res.data.code == 2002){
          ElMessage.success('评论成功');
          //评论成功后,需要立即加载评论
          loadComments(weibo.value.id);
        }
      })

}
//定义响应式变量arr保存评论数据
const arr = ref([]);
// 定义加载评论的函数
const loadComments = (id)=>{
  axios.get('http://localhost:8080/v1/comments/'+ id)
      .then((res) => {
        if (res.data.code == 2002){
          arr.value = res.data.data;
          console.log( " 返回的数据为 " + arr.value)
        }
      })
}

</script>


<style scoped>

</style>